package inf.coach.mobile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.kobjects.base64.Base64;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;

import android.widget.Button;
import android.widget.CheckBox;
import android.media.MediaPlayer.OnCompletionListener;

public class AddCommentAudio extends Activity {
	
	 public static long userid = 0;
	 public static long osmid= 0;
	MediaRecorder mediaRecorder= new MediaRecorder(); 
	File audioFile;
	private MediaPlayer mediaPlayer;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.audioanno);
        setTitle("Funktion Seite, Audio Kommentar hinzufügen");
    	Bundle bundle = this.getIntent().getExtras();      
		userid = bundle.getLong("userid");
		osmid= bundle.getLong("osmid");
        
        final Button record=(Button) findViewById(R.id.button_record);
        Button play=(Button) findViewById(R.id.button_play);
        final Button stop=(Button) findViewById(R.id.button_stop);
        final CheckBox anonym= (CheckBox)findViewById(R.id.checkBox_audio_anonym);
        final CheckBox onlyforme=(CheckBox)findViewById(R.id.checkBox_audio_onlyforme);
        
        Button send=(Button) findViewById(R.id.button_send);
        stop.setEnabled(false);
        

        record.setOnClickListener(new Button.OnClickListener() {


			public void onClick(View arg0) {
				
        		record();
        		
        		System.out.println("start...");
        		stop.setEnabled(true);
        		record.setEnabled(false);
			}
        });
        
        stop.setOnClickListener(new Button.OnClickListener() {


			public void onClick(View arg0) {
				
	            if(mediaRecorder!=null)
	            {
	            	mediaRecorder.stop();
	            }
        		
        		System.out.println("stop");
        		record.setEnabled(true);
        		stop.setEnabled(false);
			}
        });
        
        
        play.setOnClickListener(new Button.OnClickListener() {


			public void onClick(View arg0) {
				
				if (audioFile != null) {
					mediaPlayer = new MediaPlayer();
					// 为播放器设置数据文件 
					try{
					mediaPlayer.setDataSource(audioFile.getAbsolutePath());
					// 准备并且启动播放器
					mediaPlayer.prepare();
					mediaPlayer.start();
					mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
					@Override
					public void onCompletion(MediaPlayer mp) {
					setTitle("录音播放完毕.");

					}
					});
					}
					 catch (Exception e) {
						 
					 }
					}
        }
        });
        
        send.setOnClickListener(new Button.OnClickListener() {


  			public void onClick(View arg0) {
  					
  				try{
  					FileInputStream file= new FileInputStream(audioFile.getAbsolutePath());
  					ByteArrayOutputStream bos=new ByteArrayOutputStream();
  					byte[] buffer = new byte[8192];
  					int count=0;
  					while((count=file.read(buffer))>0)
  					{
  						bos.write(buffer, 0, count);
  					}
  					String uploadBuffer=new String(Base64.encode(bos.toByteArray()));
  					
  					if(ConnectionReceiver.isInternetConnected(getApplicationContext()))
  					{
  										
  						String text=webservice.createCommentAudio(osmid, userid, uploadBuffer,anonym.isChecked(),onlyforme.isChecked());
  					System.out.println(text);
  					if (!text.equals(null) && text.equals("successful")) {
                        dialog();
  					}
  					if (text.equals(null) || text.equals("failed")) {
  						message.show(AddCommentAudio.this,"Fehlgeschlagen", "Annotation hinzuzufügen fehlgeschlagen, bitte überprüfen Internetverbindung! ");
  					}
  					}
  					
  				}
  				catch(Exception e){
  					
  				}
  				
  			}
          });
   
        
    }
    
    private void record(){ 
    	
    	try {
    	
        /** 
         * mediaRecorder.setAudioSource设置声音来源。 
         * MediaRecorder.AudioSource这个内部类详细的介绍了声音来源。 
         * 该类中有许多音频来源，不过最主要使用的还是手机上的麦克风，MediaRecorder.AudioSource.MIC 
         */  
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);  
        /** 
         * mediaRecorder.setOutputFormat代表输出文件的格式。该语句必须在setAudioSource之后，在prepare之前。 
         * OutputFormat内部类，定义了音频输出的格式，主要包含MPEG_4、THREE_GPP、RAW_AMR……等。 
         */  
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);  
        /** 
         * mediaRecorder.setAddioEncoder()方法可以设置音频的编码 
         * AudioEncoder内部类详细定义了两种编码：AudioEncoder.DEFAULT、AudioEncoder.AMR_NB 
         */  
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);  
        /** 
         * 设置录音之后，保存音频文件的位置 
         */  
        audioFile = File.createTempFile("record_", ".3gp",EnvironmentShare.getAudioRecordDir());
        mediaRecorder.setOutputFile(audioFile.getAbsolutePath());  
          
        /** 
         * 调用start开始录音之前，一定要调用prepare方法。 
         */   
            mediaRecorder.prepare();  
            mediaRecorder.start();  
        } catch (IllegalStateException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    	
 
          
    } 
    
    protected void dialog() { 
        AlertDialog.Builder builder = new Builder(AddCommentAudio.this); 
        builder.setMessage("kommentar Hinzugefügt. Automatisch zur letzten Seite zurück!"); 
        builder.setTitle("Erfolg"); 
        builder.setPositiveButton("ok", 
                new android.content.DialogInterface.OnClickListener() { 
                    @Override 
                    public void onClick(DialogInterface dialog, int which) { 
                        dialog.dismiss(); 
                        AddCommentAudio.this.finish();
                    }

                }); 
        
        builder.create().show(); 
    } 
    
 
    protected void dialoggoback() { 
        AlertDialog.Builder builder = new Builder(AddCommentAudio.this); 
        builder.setMessage("Möchten Sie zur letzten Seite zurück springen?"); 
        builder.setTitle("Information"); 
        builder.setPositiveButton("ok", 
                new android.content.DialogInterface.OnClickListener() { 
                    @Override 
                    public void onClick(DialogInterface dialog, int which) { 
                        dialog.dismiss(); 
                        AddCommentAudio.this.finish(); 
                    }

                }); 
        builder.setNegativeButton("abbrechen", 
                new android.content.DialogInterface.OnClickListener() { 
                    @Override 
                    public void onClick(DialogInterface dialog, int which) { 
                        dialog.dismiss(); 
                    } 
                }); 
        builder.create().show(); 
    } 
    @Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) { 
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { 
            dialoggoback(); 
            return false; 
        } 
        return false; 
    }
    
   

}
    



